package org.pada.domain.config.consumer;

import org.pada.domain.config.provider.RpcProviderScanRegister;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Optional;
import java.util.Set;

/**
 * @author shen.peng
 * @since 2024/9/14
 */
@Component
public class RpcConsumerScanRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

    private ResourceLoader resourceLoader;

    private Environment environment;
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false,
                environment) {
            @Override
            protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
                return beanDefinition.getMetadata().isIndependent() && !beanDefinition.getMetadata().isAnnotation();
            }
        };
        scanner.setResourceLoader(resourceLoader);
        scanner.addIncludeFilter(new AnnotationTypeFilter(RpcConsumerConfig.class));
        Set<String> basePackage = RpcProviderScanRegister.getBasePackage(importingClassMetadata, RpcConsumerScan.class);
        for (String pkg : basePackage) {
            Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(pkg);
            for (BeanDefinition candidate : beanDefinitions) {
                if (candidate instanceof AnnotatedBeanDefinition) {
                    AnnotationMetadata metadata = ((AnnotatedBeanDefinition) candidate).getMetadata();
                    String className = metadata.getClassName();
                    Class<?> beanClass = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader());
                    Arrays.stream(beanClass.getDeclaredFields()).forEach(x -> {
                        Class<?> type = x.getType();
                        Optional<RpcConsumer> annotation = Optional.ofNullable(x.getAnnotation(RpcConsumer.class));
                        String domain = annotation.map(RpcConsumer::domain).orElse("");
                        if (!StringUtils.hasText(domain)) {
                            domain = "http://127.0.0.1";
                        }
                        Integer mode = annotation.map(RpcConsumer::mode).orElse(0);
                        AbstractBeanDefinition rawBeanDefinition = BeanDefinitionBuilder
                                .genericBeanDefinition(type).getRawBeanDefinition();
                        rawBeanDefinition.setBeanClass(RpcConsumerBeanFactory.class);
                        rawBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(type);
                        rawBeanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, domain);
                        rawBeanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(2, mode);
                        registry.registerBeanDefinition(ClassUtils.getShortName(type), rawBeanDefinition);
                    });
                }
            }
        }
    }
}
